// 质检管理相关API
import type { QualityException, QualityRecord, QualityDeduction, QualityAddition } from '@/types'

// 模拟数据库
const mockDatabase = {
  exceptions: [
    {
      id: 1,
      userId: 1001,
      userName: '张三',
      userPhone: '13800138001',
      deviceId: 1,
      deviceName: '智能回收箱A01',
      deviceCode: 'SRB-A01',
      bagNumber: 'BD202401001',
      type: 'weight_error',
      wasteType: '纸壳类',
      weight: 2.5,
      originalAmount: 5.20,
      adjustAmount: -1.20,
      description: '投放重量与系统检测重量差异较大，疑似称重异常',
      status: 'pending',
      inspectorId: null,
      inspectorName: null,
      createdAt: '2024-01-15 14:30:00',
      updatedAt: '2024-01-15 14:30:00',
      images: [
        '/images/exception1-1.jpg',
        '/images/exception1-2.jpg'
      ]
    },
    {
      id: 2,
      userId: 1002,
      userName: '李四',
      userPhone: '13800138002',
      deviceId: 2,
      deviceName: '智能回收箱B02',
      deviceCode: 'SRB-B02',
      bagNumber: 'BD202401002',
      type: 'type_error',
      wasteType: '织物类',
      weight: 1.8,
      originalAmount: 3.60,
      adjustAmount: +0.80,
      description: '投放物品类型与选择类型不符，实际为混合垃圾',
      status: 'processing',
      inspectorId: 2001,
      inspectorName: '质检员王五',
      createdAt: '2024-01-14 16:20:00',
      updatedAt: '2024-01-15 09:15:00'
    },
    {
      id: 3,
      userId: 1003,
      userName: '王五',
      userPhone: '13800138003',
      deviceId: 1,
      deviceName: '智能回收箱A01',
      deviceCode: 'SRB-A01',
      bagNumber: 'BD202401003',
      type: 'amount_error',
      wasteType: '混合类',
      weight: 3.2,
      originalAmount: 8.50,
      adjustAmount: -2.10,
      description: '计算金额异常，超出正常范围',
      status: 'completed',
      inspectorId: 2002,
      inspectorName: '质检员赵六',
      createdAt: '2024-01-13 11:45:00',
      updatedAt: '2024-01-14 10:30:00'
    },
    {
      id: 4,
      userId: 1004,
      userName: '赵六',
      userPhone: '13800138004',
      deviceId: 3,
      deviceName: '智能回收箱C03',
      deviceCode: 'SRB-C03',
      bagNumber: 'BD202401004',
      type: 'amount_error',
      wasteType: '纸壳类',
      weight: 4.5,
      originalAmount: 9.00,
      adjustAmount: +1.50,
      description: '系统计算金额偏低，实际应为更高价格',
      status: 'completed',
      inspectorId: 2001,
      inspectorName: '质检员王五',
      createdAt: '2024-01-12 10:15:00',
      updatedAt: '2024-01-13 14:20:00'
    },
    {
      id: 5,
      userId: 1005,
      userName: '钱七',
      userPhone: '13800138005',
      deviceId: 2,
      deviceName: '智能回收箱B02',
      deviceCode: 'SRB-B02',
      bagNumber: 'BD202401005',
      type: 'weight_error',
      wasteType: '混合类',
      weight: 2.8,
      originalAmount: 5.60,
      adjustAmount: -0.90,
      description: '称重设备校准问题，实际重量偏轻',
      status: 'pending',
      inspectorId: null,
      inspectorName: null,
      createdAt: '2024-01-16 09:30:00',
      updatedAt: '2024-01-16 09:30:00'
    }
  ],
  records: [
    {
      id: 1,
      exceptionId: 3,
      inspectorId: 2002,
      inspectorName: '质检员赵六',
      actionType: 'adjust',
      originalAmount: 8.50,
      adjustAmount: 6.40,
      finalAmount: 6.40,
      reason: '重新计算后发现金额确实偏高，调整为合理价格',
      inspectorNote: '已核实重量和类型，按标准价格重新计算',
      status: 'completed',
      createdAt: '2024-01-14 10:30:00'
    }
  ],
  deductions: [
    {
      id: 1,
      userId: 1001,
      userName: '张三',
      userPhone: '13800138001',
      exceptionId: 1,
      amount: 2.50,
      reason: '投放异物导致设备损坏，扣除维修费用',
      status: 'completed',
      operatorId: 2001,
      operatorName: '质检员王五',
      createdAt: '2024-01-15 15:20:00'
    }
  ],
  additions: [
    {
      id: 1,
      userId: 1002,
      userName: '李四',
      userPhone: '13800138002',
      exceptionId: 2,
      amount: 1.20,
      reason: '系统误判，补偿用户损失',
      status: 'completed',
      operatorId: 2002,
      operatorName: '质检员赵六',
      createdAt: '2024-01-15 16:45:00'
    }
  ]
}

// 获取异常列表
export const getExceptionList = (params: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { page = 1, size = 20, userName, deviceId, exceptionType, status } = params
      let filteredData = [...mockDatabase.exceptions]

      // 筛选逻辑
      if (userName) {
        filteredData = filteredData.filter(item =>
          item.userName.includes(userName) || item.userPhone.includes(userName)
        )
      }
      if (deviceId) {
        filteredData = filteredData.filter(item => item.deviceId === deviceId)
      }
      if (exceptionType) {
        filteredData = filteredData.filter(item => item.type === exceptionType)
      }
      if (status) {
        filteredData = filteredData.filter(item => item.status === status)
      }

      const total = filteredData.length
      const start = (page - 1) * size
      const end = start + size
      const list = filteredData.slice(start, end)

      resolve({
        code: 200,
        data: {
          list,
          total,
          page,
          size
        }
      })
    }, 300)
  })
}

// 处理异常
export const processException = (data: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { exceptionId, actionType, finalAmount, reason, inspectorNote } = data

      // 更新异常状态
      const exception = mockDatabase.exceptions.find(item => item.id === exceptionId)
      if (exception) {
        exception.status = 'completed'
        exception.inspectorId = 2001 // 当前质检员ID
        exception.inspectorName = '当前质检员'
        exception.updatedAt = new Date().toISOString().replace('T', ' ').substring(0, 19)
      }

      // 创建质检记录
      const record = {
        id: mockDatabase.records.length + 1,
        exceptionId,
        inspectorId: 2001,
        inspectorName: '当前质检员',
        actionType,
        originalAmount: exception?.originalAmount || 0,
        adjustAmount: data.adjustAmount || 0,
        finalAmount,
        reason,
        inspectorNote,
        status: 'completed',
        createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19)
      }
      mockDatabase.records.push(record)

      // 根据处理类型创建扣款或补款记录
      if (actionType === 'deduct' && data.adjustAmount > 0) {
        const deduction = {
          id: mockDatabase.deductions.length + 1,
          userId: exception?.userId || 0,
          userName: exception?.userName || '',
          userPhone: exception?.userPhone || '',
          exceptionId,
          amount: data.adjustAmount,
          reason,
          status: 'completed',
          operatorId: 2001,
          operatorName: '当前质检员',
          createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19)
        }
        mockDatabase.deductions.push(deduction)
      } else if (actionType === 'compensate' && data.adjustAmount > 0) {
        const addition = {
          id: mockDatabase.additions.length + 1,
          userId: exception?.userId || 0,
          userName: exception?.userName || '',
          userPhone: exception?.userPhone || '',
          exceptionId,
          amount: data.adjustAmount,
          reason,
          status: 'completed',
          operatorId: 2001,
          operatorName: '当前质检员',
          createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19)
        }
        mockDatabase.additions.push(addition)
      }

      resolve({
        code: 200,
        message: '处理成功',
        data: record
      })
    }, 500)
  })
}

// 获取质检记录列表
export const getQualityRecords = (params: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { page = 1, size = 20 } = params
      const total = mockDatabase.records.length
      const start = (page - 1) * size
      const end = start + size
      const list = mockDatabase.records.slice(start, end)

      resolve({
        code: 200,
        data: {
          list,
          total,
          page,
          size
        }
      })
    }, 300)
  })
}

// 获取扣款记录列表
export const getDeductionRecords = (params: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { page = 1, size = 20 } = params
      const total = mockDatabase.deductions.length
      const start = (page - 1) * size
      const end = start + size
      const list = mockDatabase.deductions.slice(start, end)

      resolve({
        code: 200,
        data: {
          list,
          total,
          page,
          size
        }
      })
    }, 300)
  })
}

// 获取补款记录列表
export const getAdditionRecords = (params: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { page = 1, size = 20 } = params
      const total = mockDatabase.additions.length
      const start = (page - 1) * size
      const end = start + size
      const list = mockDatabase.additions.slice(start, end)

      resolve({
        code: 200,
        data: {
          list,
          total,
          page,
          size
        }
      })
    }, 300)
  })
}

// 创建扣款记录
export const createDeduction = (data: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const deduction = {
        id: mockDatabase.deductions.length + 1,
        ...data,
        status: 'completed',
        operatorId: 2001,
        operatorName: '当前质检员',
        createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19)
      }
      mockDatabase.deductions.push(deduction)

      resolve({
        code: 200,
        message: '扣款成功',
        data: deduction
      })
    }, 500)
  })
}

// 创建补款记录
export const createAddition = (data: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const addition = {
        id: mockDatabase.additions.length + 1,
        ...data,
        status: 'completed',
        operatorId: 2001,
        operatorName: '当前质检员',
        createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19)
      }
      mockDatabase.additions.push(addition)

      resolve({
        code: 200,
        message: '补款成功',
        data: addition
      })
    }, 500)
  })
}

// 获取用户投递记录列表（用于新增异常）
export const getUserDeliveryRecords = (params: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟用户投递记录数据
      const deliveryRecords: UserDeliveryRecord[] = [
        {
          id: 1,
          userId: 1001,
          userName: '张三',
          userPhone: '13800138001',
          deviceId: 1,
          deviceName: '智能回收箱A01',
          deviceCode: 'SRB-A01',
          bagNumber: 'BD202401001',
          wasteType: '纸壳类',
          weight: 2.5,
          amount: 5.20,
          deliveryTime: '2024-01-15 14:30:00',
          images: ['/images/delivery1-1.jpg', '/images/delivery1-2.jpg']
        },
        {
          id: 2,
          userId: 1002,
          userName: '李四',
          userPhone: '13800138002',
          deviceId: 2,
          deviceName: '智能回收箱B02',
          deviceCode: 'SRB-B02',
          bagNumber: 'BD202401002',
          wasteType: '织物类',
          weight: 1.8,
          amount: 3.60,
          deliveryTime: '2024-01-15 15:20:00'
        },
        {
          id: 3,
          userId: 1003,
          userName: '王五',
          userPhone: '13800138003',
          deviceId: 1,
          deviceName: '智能回收箱A01',
          deviceCode: 'SRB-A01',
          bagNumber: 'BD202401003',
          wasteType: '混合类',
          weight: 3.2,
          amount: 8.50,
          deliveryTime: '2024-01-15 16:10:00'
        },
        {
          id: 4,
          userId: 1004,
          userName: '赵六',
          userPhone: '13800138004',
          deviceId: 3,
          deviceName: '智能回收箱C03',
          deviceCode: 'SRB-C03',
          bagNumber: 'BD202401004',
          wasteType: '纸壳类',
          weight: 4.5,
          amount: 9.00,
          deliveryTime: '2024-01-15 17:05:00'
        },
        {
          id: 5,
          userId: 1005,
          userName: '钱七',
          userPhone: '13800138005',
          deviceId: 2,
          deviceName: '智能回收箱B02',
          deviceCode: 'SRB-B02',
          bagNumber: 'BD202401005',
          wasteType: '混合类',
          weight: 2.8,
          amount: 5.60,
          deliveryTime: '2024-01-15 18:30:00'
        }
      ]

      const { page = 1, size = 20, bagNumber, userName } = params
      let filteredData = [...deliveryRecords]

      // 筛选逻辑
      if (bagNumber) {
        filteredData = filteredData.filter(item => item.bagNumber.includes(bagNumber))
      }
      if (userName) {
        filteredData = filteredData.filter(item =>
          item.userName.includes(userName) || item.userPhone.includes(userName)
        )
      }

      const total = filteredData.length
      const start = (page - 1) * size
      const end = start + size
      const list = filteredData.slice(start, end)

      resolve({
        code: 200,
        data: {
          list,
          total,
          page,
          size
        }
      })
    }, 300)
  })
}

// 创建异常记录
export const createException = (data: CreateExceptionForm) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 获取对应的投递记录
      const deliveryRecords = [
        {
          id: 1,
          userId: 1001,
          userName: '张三',
          userPhone: '13800138001',
          deviceId: 1,
          deviceName: '智能回收箱A01',
          deviceCode: 'SRB-A01',
          bagNumber: 'BD202401001',
          wasteType: '纸壳类',
          weight: 2.5,
          amount: 5.20,
          deliveryTime: '2024-01-15 14:30:00'
        }
      ]

      const deliveryRecord = deliveryRecords.find(item => item.id === data.deliveryRecordId)

      if (!deliveryRecord) {
        resolve({
          code: 400,
          message: '投递记录不存在'
        })
        return
      }

      // 创建异常记录
      const exception: QualityException = {
        id: mockDatabase.exceptions.length + 1,
        userId: deliveryRecord.userId,
        userName: deliveryRecord.userName,
        userPhone: deliveryRecord.userPhone,
        deviceId: deliveryRecord.deviceId,
        deviceName: deliveryRecord.deviceName,
        deviceCode: deliveryRecord.deviceCode,
        bagNumber: deliveryRecord.bagNumber,
        type: data.type,
        wasteType: deliveryRecord.wasteType,
        weight: deliveryRecord.weight,
        originalAmount: deliveryRecord.amount,
        adjustAmount: data.adjustAmount,
        description: data.description,
        status: 'pending',
        inspectorId: 2001, // 当前质检员
        inspectorName: '当前质检员',
        createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19),
        updatedAt: new Date().toISOString().replace('T', ' ').substring(0, 19)
      }

      mockDatabase.exceptions.push(exception)

      // 创建质检记录
      const record: QualityRecord = {
        id: mockDatabase.records.length + 1,
        exceptionId: exception.id,
        inspectorId: 2001,
        inspectorName: '当前质检员',
        actionType: data.adjustAmount > 0 ? 'compensate' : 'deduct',
        originalAmount: deliveryRecord.amount,
        adjustAmount: data.adjustAmount,
        finalAmount: deliveryRecord.amount + data.adjustAmount,
        reason: data.reason,
        inspectorNote: data.description,
        status: 'completed',
        createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19)
      }

      mockDatabase.records.push(record)

      resolve({
        code: 200,
        message: '异常创建成功',
        data: exception
      })
    }, 500)
  })
}

export const mockQualityAPI = {
  getExceptionList,
  processException,
  getQualityRecords,
  getDeductionRecords,
  getAdditionRecords,
  createDeduction,
  createAddition,
  getUserDeliveryRecords,
  createException
}
